// pages/village/village.js
const app = getApp()

Page({
  data: {
    posts: [],
    isLoading: true,
    mainTab: 0, // 0: 关注, 1: 推荐, 2: 同城
    subTab: 0   // 0: 全部, 1: 关注, 2: 喜欢
  },

  onLoad() {
    this.checkAuthAndLoadData();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.loadPosts();
    }
  },

  // 检查授权并加载数据
  checkAuthAndLoadData() {
    if (app.globalData.userInfo) {
      this.loadPosts();
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  // 加载帖子
  loadPosts() {
    this.setData({ isLoading: true });

    // 使用模拟数据
    if (app.globalData.useMockData) {
      setTimeout(() => {
        // 获取当前日期
        const now = new Date();
        
        // 昨天的日期
        const yesterday = new Date(now);
        yesterday.setDate(now.getDate() - 1);
        const yesterdayStr = yesterday.toISOString().split('T')[0] + ' 15:30';
        
        // 5天前的日期
        const fiveDaysAgo = new Date(now);
        fiveDaysAgo.setDate(now.getDate() - 5);
        const fiveDaysAgoStr = fiveDaysAgo.toISOString().split('T')[0] + ' 10:20';
        
        // 超过20天的日期（用于测试年月日显示）
        const oldDate = new Date(now);
        oldDate.setDate(now.getDate() - 25);
        const oldDateStr = oldDate.toISOString().split('T')[0] + ' 09:15';

        const mockPosts = [
          {
            id: '3001',
            user: {
              id: '1001',
              nickname: '小可爱',
              avatar_url: '',
              gender: 'female',
              birth_year: 2001,
              city: '杭州',
              education: '本科',
              major: '艺术设计',
              verified: true,
              is_followed: true,
              is_liked_user: false
            },
            content: '今天去了西湖，风景真的太美了！有没有小伙伴也喜欢旅游的？可以一起组队呀～',
            images: [
              'https://images.unsplash.com/photo-1542662565-7e4b66bae529?w=400&h=300&fit=crop',
              'https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=400&h=300&fit=crop',
              'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop'
            ],
            likes: 128,
            comments: 45,
            shares: 12,
            is_liked: false,
            create_time: '2024-10-08 14:30',
            tags: ['旅行', '杭州', '西湖']
          },
          {
            id: '3002',
            user: {
              id: '1002',
              nickname: '阳光男孩',
              avatar_url: '',
              gender: 'male',
              birth_year: 1995,
              city: '上海',
              education: '硕士',
              major: '计算机科学',
              verified: true,
              is_followed: false,
              is_liked_user: true
            },
            content: '周末篮球局，有一起的吗？在徐家汇体育公园，新手老手都欢迎！',
            images: [
              'https://images.unsplash.com/photo-1546519638-68e109498ffc?w=400&h=300&fit=crop',
              'https://images.unsplash.com/photo-1519861155730-0a84f4e0b7e5?w=400&h=300&fit=crop'
            ],
            likes: 89,
            comments: 23,
            shares: 5,
            is_liked: true,
            create_time: '2024-10-08 12:15',
            tags: ['运动', '篮球', '上海']
          },
          {
            id: '3003',
            user: {
              id: '1003',
              nickname: '文艺青年',
              avatar_url: '',
              gender: 'male',
              birth_year: 1993,
              city: '北京',
              education: '博士',
              major: '文学',
              verified: false,
              is_followed: false,
              is_liked_user: true
            },
            content: '最近在读《百年孤独》，有读过的小伙伴可以一起交流读书心得吗？',
            images: [
              'https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=400&h=300&fit=crop'
            ],
            likes: 67,
            comments: 18,
            shares: 3,
            is_liked: false,
            create_time: '2024-10-07 20:45',
            tags: ['读书', '文学', '交流']
          },
          {
            id: '3004',
            user: {
              id: '1004',
              nickname: '美食达人',
              avatar_url: '',
              gender: 'female',
              birth_year: 1998,
              city: '成都',
              education: '本科',
              major: '食品科学',
              verified: true,
              is_same_city: true
            },
            content: '昨天发现了一家超棒的火锅店，味道正宗，环境也很不错！推荐给大家～',
            images: [
              'https://images.unsplash.com/photo-1555949963-aa79dcee981c?w=400&h=300&fit=crop',
              'https://images.unsplash.com/photo-1546833999-b9f581a1996d?w=400&h=300&fit=crop'
            ],
            likes: 156,
            comments: 32,
            shares: 8,
            is_liked: false,
            create_time: yesterdayStr,
            tags: ['美食', '火锅', '成都']
          },
          {
            id: '3005',
            user: {
              id: '1005',
              nickname: '运动健将',
              avatar_url: '',
              gender: 'male',
              birth_year: 1996,
              city: '广州',
              education: '硕士',
              major: '体育教育',
              verified: false
            },
            content: '5天前参加了马拉松比赛，虽然很累但很有成就感！坚持运动真的能改变生活。',
            images: [
              'https://images.unsplash.com/photo-1552674605-db6ffd4facb5?w=400&h=300&fit=crop'
            ],
            likes: 203,
            comments: 45,
            shares: 15,
            is_liked: true,
            create_time: fiveDaysAgoStr,
            tags: ['运动', '马拉松', '健康']
          },
          {
            id: '3006',
            user: {
              id: '1006',
              nickname: '旅行家',
              avatar_url: '',
              gender: 'female',
              birth_year: 1992,
              city: '西安',
              education: '本科',
              major: '旅游管理',
              verified: true
            },
            content: '25天前去西安旅游，参观了兵马俑，感受到了中华文明的博大精深！',
            images: [
              'https://images.unsplash.com/photo-1542662565-7e4b66bae529?w=400&h=300&fit=crop',
              'https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=400&h=300&fit=crop'
            ],
            likes: 89,
            comments: 21,
            shares: 6,
            is_liked: false,
            create_time: oldDateStr,
            tags: ['旅行', '西安', '兵马俑']
          }
        ];

        // 预处理数据，确保出生年正确显示，并格式化发布日期
        const processedPosts = mockPosts.map(post => {
          const user = { ...post.user };
          // 处理出生年显示，确保两位数格式
          if (user.birth_year) {
            user.formatted_birth_year = (user.birth_year % 100).toString().padStart(2, '0') + '年';
          }
          // 格式化发布日期
          const formattedPost = { ...post, user };
          formattedPost.formatted_create_time = this.formatCreateTime(post.create_time);
          return formattedPost;
        });

        // 根据子选项卡筛选数据
        let filteredPosts = processedPosts;
        if (this.data.mainTab === 0) { // 关注页面
          if (this.data.subTab === 1) { // 关注筛选
            filteredPosts = processedPosts.filter(post => post.user.is_followed);
          } else if (this.data.subTab === 2) { // 喜欢筛选
            filteredPosts = processedPosts.filter(post => post.user.is_liked_user);
          }
        }

        this.setData({
          posts: filteredPosts,
          isLoading: false
        });
      }, 1000);
      return;
    }

    // 实际API调用逻辑
    this.loadPostsFromAPI();
  },

  // 从API加载帖子
  async loadPostsFromAPI() {
    try {
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/posts`,
        method: 'GET',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        },
        data: {
          type: this.data.mainTab === 0 ? 'following' : this.data.mainTab === 1 ? 'recommend' : 'local'
        }
      });

      if (result.data.success) {
        this.setData({
          posts: result.data.data.posts || [],
          isLoading: false
        });
      } else {
        app.showError(result.data.message || '加载失败');
        this.setData({ isLoading: false });
      }
    } catch (error) {
      console.error('加载帖子失败:', error);
      app.showError('网络错误，请重试');
      this.setData({ isLoading: false });
    }
  },

  // 切换主选项卡
  switchMainTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({
      mainTab: tab
    });
    this.loadPosts();
  },

  // 切换子选项卡
  switchSubTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({
      subTab: tab
    });
    this.loadPosts();
  },

  // 点赞/取消点赞
  toggleLike(e) {
    const postId = e.currentTarget.dataset.postId;
    const posts = this.data.posts.map(post => {
      if (post.id === postId) {
        const newLikeStatus = !post.is_liked;
        return {
          ...post,
          is_liked: newLikeStatus,
          likes: newLikeStatus ? post.likes + 1 : post.likes - 1
        };
      }
      return post;
    });

    this.setData({ posts });

    // 如果是模拟数据模式，不需要调用API
    if (app.globalData.useMockData) {
      console.log('模拟数据模式：点赞状态已更新');
      return;
    }

    // API调用
    this.toggleLikeAPI(postId);
  },

  // API点赞/取消点赞
  async toggleLikeAPI(postId) {
    try {
      const post = this.data.posts.find(p => p.id === postId);
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/posts/${postId}/like`,
        method: 'POST',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        },
        data: { like: post.is_liked }
      });

      if (!result.data.success) {
        app.showError(result.data.message || '操作失败');
        // 回滚状态
        const posts = this.data.posts.map(p => {
          if (p.id === postId) {
            return {
              ...p,
              is_liked: !p.is_liked,
              likes: p.is_liked ? p.likes - 1 : p.likes + 1
            };
          }
          return p;
        });
        this.setData({ posts });
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      app.showError('操作失败');
      // 回滚状态
      const posts = this.data.posts.map(p => {
        if (p.id === postId) {
          return {
            ...p,
            is_liked: !p.is_liked,
            likes: p.is_liked ? p.likes - 1 : p.likes + 1
          };
        }
        return p;
      });
      this.setData({ posts });
    }
  },

  // 评论 - 跳转到动态详情页面
  commentPost(e) {
    const postId = e.currentTarget.dataset.postId;
    wx.navigateTo({
      url: `/pages/post/detail?postId=${postId}`
    });
  },

  // 分享
  sharePost(e) {
    const postId = e.currentTarget.dataset.postId;
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 查看用户详情
  viewUserDetail(e) {
    const userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `/pages/user/detail?userId=${userId}`
    });
  },

  // 发布新帖子
  createPost() {
    wx.navigateTo({
      url: '/pages/post/create'
    });
  },

  // 格式化创建时间
  formatCreateTime(createTime) {
    if (!createTime) return '';
    
    const now = new Date();
    const postDate = new Date(createTime);
    const diffTime = now.getTime() - postDate.getTime();
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
      // 今天，显示时间
      const hours = postDate.getHours().toString().padStart(2, '0');
      const minutes = postDate.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    } else if (diffDays >= 1 && diffDays <= 20) {
      // 1-20天内，显示相对时间
      if (diffDays === 1) {
        return '昨天';
      } else {
        return `${diffDays}天前`;
      }
    } else {
      // 超过20天，显示具体年月日
      const year = postDate.getFullYear();
      const month = (postDate.getMonth() + 1).toString().padStart(2, '0');
      const day = postDate.getDate().toString().padStart(2, '0');
      return `${year}年${month}月${day}日`;
    }
  },

  // 图片加载错误处理
  onImageError(e) {
    console.log('图片加载失败:', e.detail.errMsg);
    // 可以在这里添加默认图片替换逻辑
  },

  // 刷新帖子
  refreshPosts() {
    this.loadPosts();
  }
})
